home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: presby.edu!jtbell
- From: jtbell@presby.edu (Jon Bell)
- Subject: Re: Arrays or Pointers?
- Message-ID: <DpKEyB.I5K@presby.edu>
- Date: Mon, 8 Apr 1996 22:39:46 GMT
- References: <4kbsk3$f07@zeus.tcp.co.uk>
- Organization: Presbyterian College, Clinton, South Carolina USA
-
- David <daveg@tcp.co.uk> wrote:
- >I'm currently on a C++ course and we seem to be using pointers a fair
- >bit. On questioning this, was told that pointers where quicker than
- >using arrays. In which situations should I be using arrays over
- >pointers and vice versa?
-
- Suppose you have the following array:
-
- double foo[100];
-
- You can find the sum of the elements of the array either using
-
- sum = 0;
- for (int k = 0; k < 100; k++)
- sum += foo[k];
-
- or using something like
-
- sum = 0;
- double *p;
- p = foo;
- for (int k = 0; k < 100; k++)
- sum += *p++;
-
- If you have a really simple-minded compiler, for the first option it will
- generate code that re-calculates the address of foo[k] from scratch every
- time around the loop (which usually means a multiplication and an
- addition), instead of advancing a pointer through the array (a simple
- addition) as in the second option.
-
- However, a reasonably smart compiler can generate the same code for both
- situations, as someone else has already pointed out. I myself prefer to
- use array notation unless I absolutely have to use pointers, because it's
- easier for me to make mistakes if I use pointers. (So if I got the
- details of the pointer example wrong, then it's also an example of why I
- prefer arrays! :-))
-
- --
- Jon Bell <jtbell@presby.edu> Presbyterian College
- Dept. of Physics and Computer Science Clinton, South Carolina USA
-